package com.vote.www.utils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.Map.Entry;

/**
 * 实体转换器
 * @author 汤伟杰
 *
 */
public  class ConvertObj {
    /**
	 * 把实体转换成Map
	 * @param target
	 * @return
	 */
	public static Map<String,Object> toMap(Object target) {
		Map<String, Object> reMap = new HashMap<String, Object>();
		try {
			if(target!=null){
				transforMap(target,target.getClass(), reMap);
				return reMap;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new HashMap<String, Object>();
	}
	public static <T> Map<String,Object> beanToMap(T target) {
		Map<String, Object> reMap = new HashMap<String, Object>();
		if (target == null)
			return null;
		try {
			transforMap(target,target.getClass(), reMap);
			return reMap;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new HashMap<String, Object>();
	}

	/**
	 * 把实体和实体的继承类转换成Map
	 * @param target
	 * @return
	 */
	public static Map<String,Object> toMapExtends(Object target) {
		try {
			Map<String, Object> reMap = new HashMap<String, Object>();
			if (target == null)
				return new HashMap<String, Object>();;
			transforMap(target,target.getClass(),reMap);
			Object object =target;
			Class<?> clazz;
			while((clazz = object.getClass().getSuperclass())!=null){
				object = clazz.newInstance();
				if(object instanceof Serializable){
					transforMap(target,object.getClass(), reMap);
				}
			}
			return reMap;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new HashMap<String, Object>();
	}
	/**
	 * 把实体和实体的继承类转换成Map
	 * @param <T>
	 * @param target
	 * @return
	 */
	public static <T> Map<String,Object> beanToMapExtends(T target) {
		try {
			Map<String, Object> reMap = new HashMap<String, Object>();
			if (target == null)
				return new HashMap<String, Object>();;
			transforMap(target,target.getClass(),reMap);
			Object object =target;
			Class<?> clazz;
			while((clazz = object.getClass().getSuperclass())!=null){
				object = clazz.newInstance();
//				if(object instanceof Serializable){
					transforMap(target,object.getClass(), reMap);
//				}
			}
			return reMap;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new HashMap<String, Object>();
	}

	private static void transforMap(Object target, Class<?> clazz, Map<String, Object> reMap) throws Exception {
		Field[] fields = clazz.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			Field f = clazz.getDeclaredField(fields[i].getName());
			f.setAccessible(true);
			Object o = f.get(target);
			reMap.put(fields[i].getName(), o);
		}
	}
	/**
	 * 把list实体转成listMap
	 * @param <T>
	 * @param list
	 * @return
	 */
	public static <T> List<Map<String,Object>> toListMap(List<T> list){
		List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		if (list!=null&&list.size()!=0) {
			for (T li : list) {
				try {
					listMap.add(beanToMapExtends(li));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.err.println("list<T> fail to listMap!");
					e.printStackTrace();
				}
			} 
		}
		return listMap;
	}
	public static <T> T map2Bean(T t,Map map) throws Exception {
	    Class clazz = t.getClass();
	    //实例化类  
	    T entity = (T)clazz.newInstance();  
	    Set<String> keys = map.keySet();
	    //变量map 赋值  
	    for(String key:keys){
	        String fieldName = key;
	        //判断是sql 还是hql返回的结果  
	        if(key.equals(key.toUpperCase())){  
	            //获取所有域变量  
	            Field[] fields = clazz.getDeclaredFields();
	            for(Field field: fields){
	                if(field.getName().toUpperCase().equals(key)) fieldName=field.getName();  
	                break;  
	            }  
	        }  
	        //设置赋值  
	        try {  
	            //参数的类型  clazz.getField(fieldName)  
	            Class<?> paramClass = clazz.getDeclaredField(fieldName).getType();
	            //拼装set方法名称  
	            String methodName = "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
	            //根据名称获取方法  
	            Method method = clazz.getMethod(methodName, paramClass);
	            //调用invoke执行赋值  
	            method.invoke(entity, map.get(key));  
	        } catch (Exception e) {
	            //NoSuchMethod  
	        }  
	    }  
	      
	    return entity;  
	}  
	/**
	 * 把 字符串分类变成一个集合，通过逗号分开
	 * @param listMap
	 * @param classifyName
	 */
	public static void strToList(List<Map<String, Object>> listMap, String classifyName) {
		List<String> listPicPath;
		String picPaths;
		for(int i=0;i<listMap.size();i++){
			
			picPaths =(String) listMap.get(i).get(classifyName);
			listPicPath = new ArrayList<String>();
			if(picPaths!=null){
				for(String picPath:picPaths.split(",")){
					listPicPath.add(picPath);
				}
			}
			listMap.get(i).put(classifyName, listPicPath);
		}
	}
	
	/*public static void main(String[] args) {
		Tappuser tappuser  =new Tappuser();
		tappuser.setCreattime(new Date());
		tappuser.setBirth("2016-11-21");
		Map map = ConvertObjTo.map(tappuser);
		for(Object entry:map.entrySet()){
			Entry et = (Entry)entry;
			et.getKey();
			System.out.println(et.getKey());
			System.out.println(et.getValue());
			System.out.println("============");
		}
	}*/
	public static Map<String, String> toMapStr(Object target) {
		Map<String, String> reMap = new HashMap<String, String>();
		try {
			if(target!=null){
				Class<? extends Object> clazz = target.getClass();
				Field[] fields = clazz.getDeclaredFields();
				for (int i = 0; i < fields.length; i++) {
					Field f = clazz.getDeclaredField(fields[i].getName());
					f.setAccessible(true);
					Object o = f.get(target);
					if(o !=null ){
						reMap.put(fields[i].getName(), String.valueOf(o));
					}
				}
				return reMap;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new HashMap<String, String>();
	}
	/**
	 * 往listMap里插入map
	 * @param listMap	原map
	 * @param mapObj	要新增或替换的map
	 */
	public static void addProperties(List<Map<String, Object>> listMap, Map<String, String> mapObj) {
		for(int i=0;i<listMap.size();i++){
			listMap.get(i).putAll(mapObj);
		}
	}
	public static void convertToXML(StringBuffer xml, Map<String, Object> param) {
		// TODO Auto-generated method stub
		for(Entry<String, Object> entry:param.entrySet()){
			if(entry.getValue() instanceof Map){
				xml.append("<"+entry.getKey()+">");
				convertToXML(xml, (Map)entry.getValue());
				xml.append("</"+entry.getKey()+">");
			}else{
				xml.append("<"+entry.getKey()+">"+entry.getValue()+"</"+entry.getKey()+">\n");
			}
			
		}
	}

}
